from django import http
from django.core.cache import cache

from django.shortcuts import render

# Create your views here.
from django.views import View

from .models import Area
from meiduo_mall.utils.response_code import RETCODE


class AreaView(View):
    """省市区数据查询"""
    def get(self, request):
        # 获取area_id
        area_id = request.GET.get('area_id')
        # 如果此值为none
        # 先尝试获取缓存，如果缓存为空，则再从数据库查
        if area_id is None:
            province_list = cache.get('province_list')
            if province_list is None:
                province_qs = Area.objects.filter(parent=None)
                # 拼接json数据返回前端，用于前端提取subs
                province_list = []
                # 数据库查询字符集可以进行遍历;[{}]
                for province_model in province_qs:
                    province_list.append({
                        'id': province_model.id,
                        'name': province_model.name
                    })
                # 没有缓存,就设置缓存
                    cache.set('province_list', province_list, 3600)
            return http.JsonResponse({'code': RETCODE.OK,'errmsg':'OK','province_list': province_list})
        else:
            # 先去缓存读写数据,如果缓存中没有再去mysql
            data_dict = cache.get('sub_area' + area_id)
            # 获取到对应的记录值,获取1级的目标后再外健获取其他；
            if data_dict is None:
                parent_model = Area.objects.get(id=area_id)
                sub_qs = parent_model.subs.all()
                # sub_qs = parent_model.subs.all()
                # sub_qs = Area.objects.filter(parent_id=area_id)

                sub_list = []
                for sub_model in sub_qs:
                    sub_list.append({
                        'id': sub_model.id,
                        'name': sub_model.name
                    })
                # 包装返回前端的数据
                sub_data = {
                    'id': parent_model.id,
                    'name': parent_model.name,
                    'subs': sub_list
                }

                # 设置缓存
                cache.set('sub_area' + area_id, data_dict, 3600)
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg':'OK','sub_data': sub_data})











